/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package de.carcophan.jimdb.ejb.timer;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.annotation.PostConstruct;
import javax.ejb.Schedule;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.MultiPartEmail;

/**
 *
 * @author jheidenreich
 */
@Singleton
@Startup
public class BackupTimer {

    static Logger logger = Logger.getLogger(BackupTimer.class.getName());
    @PersistenceContext(unitName = "jimdb-warPU")
    private EntityManager em;

    @PostConstruct
    public void init() {
      logger.log(Level.INFO, "BackupTimer initialized");
    }

    @Schedule(second = "0", minute = "07", hour = "22", dayOfMonth = "*")
    public void doTimer() {
        try {
            logger.log(Level.INFO, "dumping to email");
            TimerConfig config = em.find(TimerConfig.class, "dumpargs");
            execBackup(config);
        } catch (Exception e) {
            logger.log(Level.SEVERE, "Error occurred while dumping DB to Mail", e);
        }



    }

    protected void execBackup(TimerConfig tConfig) throws InterruptedException, EmailException, IOException {
        final Process exec1 = Runtime.getRuntime().exec(new String[]{tConfig.getDumpProgName(), tConfig.getDbUser(), tConfig.getDbPass(), tConfig.getDbSchema()});

        int exitCode = exec1.waitFor();
        InputStream is = exec1.getInputStream();

        logger.log(Level.INFO, "Process returned with exit code = " + exitCode);
        if (is != null) {

            String outFilename = tConfig.getZipFileName();
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename));
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            out.putNextEntry(new ZipEntry(tConfig.getZipEntryName()));
            byte[] buffer = new byte[1024];
            try {
                int n;
                while ((n = is.read(buffer)) != -1) {

                    out.write(buffer, 0, n);
                }
            } finally {
                is.close();
                out.close();
            }
            MultiPartEmail email = new MultiPartEmail();
            email.setHostName(tConfig.getSmtpServer());
            email.setSmtpPort(tConfig.getSmtpPort());
            email.setFrom(tConfig.getMailFrom());
            email.setSubject(tConfig.getMailSubject() + new SimpleDateFormat("yyyy/MM/dd").format(new Date()));
            email.setMsg(tConfig.getMailMessage() + new Date());
            email.addTo(tConfig.getEmailRcpt());
            EmailAttachment attachment = new EmailAttachment();
            attachment.setPath(outFilename);
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
            attachment.setDescription(tConfig.getMailDescription());
            attachment.setName(tConfig.getZipFileName());
            email.attach(attachment);
            email.send();
        }
    }
}
